package com.yanqu.road.server.gameplayer.module.activity.evefeast;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.dao.impl.player.UserEveFeastDaoImpl;
import com.yanqu.road.entity.activity.evefeast.EveFeastBlock;
import com.yanqu.road.entity.activity.evefeast.EveFeastGameData;
import com.yanqu.road.entity.activity.evefeast.EveFeastItem;
import com.yanqu.road.entity.activity.evefeast.UserEveFeastData;
import com.yanqu.road.entity.activity.evefeast.config.EveFeastMissionConfig;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eShopType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.*;
import com.yanqu.road.logic.activity.evefeast.EveFeastGameLogic;
import com.yanqu.road.logic.pb.EveFeastPb;
import com.yanqu.road.pb.activity.EveFeastProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.evefeast.EveFeastMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class EveFeastModule extends GeneralModule {
    public EveFeastModule(GamePlayer player) {
        super(player);
    }

    private UserEveFeastData userData;

    private RandomHelper randomHelper = new RandomHelper();

    @Override
    public boolean loadData() {
        if (EveFeastMgr.getActivityInfo() == null || !ActivityMgr.activityInShowTime(EveFeastMgr.getActivityInfo())) {
            return true;
        }
        if (!SystemOpenMgr.systemOpen(player, eSystemId.EveFeast.getValue())) {
            return true;
        }
        userData = new UserEveFeastDaoImpl().getUserEveFeastData(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId());
        initUserData();
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        if (userData == null) {
            return true;
        }
        if (userData.isInsertOption()) {
            new UserEveFeastDaoImpl().add(userData);
        } else if (userData.isUpdateOption()) {
            new UserEveFeastDaoImpl().update(userData);
        }
        return true;
    }

    @Override
    public void loginSendMsg() {

    }

    @Override
    public void afterLogin() {
        resetOneDay(true);
        initUserData();
        syncConfigMsg();
        syncUserMsg();
    }

    public void syncUserMsg() {
        if (EveFeastMgr.getConfig() == null) {
            return;
        }

        if (EveFeastMgr.getActivityInfo() == null || !ActivityMgr.activityInShowTime(EveFeastMgr.getActivityInfo())) {
            return;
        }

        if (userData == null) {
            return;
        }

        EveFeastProto.EveFeastUserSyncMsg.Builder syncMsg = EveFeastProto.EveFeastUserSyncMsg.newBuilder();
        syncMsg.setActivityId(userData.getActivityId());
        syncMsg.setGameTimes(userData.getGameTimes());
        syncMsg.setMaxScore(userData.getMaxScore());
        syncMsg.setIsBuyToken1(userData.getBuyToken1());
        syncMsg.setIsBuyToken2(userData.getBuyToken2());
        if (userData.getGameData() != null) {
            syncMsg.setNowTurnId(userData.getGameData().getTurnId());
        }
        if (userData.getPracticeData() != null){
            syncMsg.setNowPracticeTurnId(userData.getPracticeData().getTurnId());
        }
        syncMsg.setGuideStep(userData.getGuideStep());

        player.sendPacket(ClientProtocol.U_EVEFEAST_USER_SYNC, syncMsg);
    }

    public void syncConfigMsg() {
        if (EveFeastMgr.getConfig() == null) {
            return;
        }

        if (EveFeastMgr.getActivityInfo() == null || !ActivityMgr.activityInShowTime(EveFeastMgr.getActivityInfo())) {
            return;
        }

        EveFeastProto.EveFeastConfigSyncMsg.Builder configMsg = EveFeastMgr.getConfigMsg(player.getLanguage());
        player.sendPacket(ClientProtocol.U_EVEFEAST_CONFIG_SYNC, configMsg);
    }

    public void initUserData() {
        if (!SystemOpenMgr.systemOpen(player, eSystemId.EveFeast.getValue())) {
            return;
        }

        if (EveFeastMgr.getConfig() == null) {
            return;
        }

        if (EveFeastMgr.getActivityInfo() == null || !ActivityMgr.activityInShowTime(EveFeastMgr.getActivityInfo())) {
            return;
        }

        if (userData == null || userData.getActivityId() != EveFeastMgr.getConfig().getActivityId()) {
            userData = new UserEveFeastData(EveFeastMgr.getConfig().getActivityId(), player.getUserId());
        }

    }

    public void initSystem() {
        initUserData();
        syncConfigMsg();
        syncUserMsg();
    }

    public void resetOneDay(boolean isLogin) {
        if (userData == null) {
            return;
        }

        long currentTime = DateHelper.getCurrentTime();
        if (DateHelper.isSameDay(userData.getLastGameTime() / 1000, currentTime / 1000)) {
            return;
        }
        userData.setLastGameTime(currentTime);
        userData.setGameTimes(0);
        if (!isLogin){
            syncUserMsg();
        }
    }

    public int checkActivityRet() {
        if (userData == null) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }

        if (EveFeastMgr.getConfig() == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (!ActivityMgr.activityInTime(EveFeastMgr.getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_OVER_TIME;
        }

        return 0;
    }

    /**
     * 开始游戏,mission=0是试玩 1 是正式
     *
     * @param missionId
     * @return
     */
    public int startGame(int missionId) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        if (missionId != 0 && userData.getGameData() != null) { //不为空直接返回游戏数据
            EveFeastProto.EveFeastGameTemp.Builder gameMsg = EveFeastPb.parseGameDataMsg(userData.getGameData());
            EveFeastProto.EveFeastEnterGameRespMsg.Builder respMsg = EveFeastProto.EveFeastEnterGameRespMsg.newBuilder();
            respMsg.setRet(0);
            respMsg.setGameScene(gameMsg);
            player.sendPacket(ClientProtocol.U_EVEFEAST_ENTER_GAME, respMsg);
            return 0;
        }

        if (missionId == 0 && userData.getPracticeData() != null) {
            EveFeastProto.EveFeastGameTemp.Builder gameMsg = EveFeastPb.parseGameDataMsg(userData.getPracticeData());
            EveFeastProto.EveFeastEnterGameRespMsg.Builder respMsg = EveFeastProto.EveFeastEnterGameRespMsg.newBuilder();
            respMsg.setRet(0);
            respMsg.setGameScene(gameMsg);
            player.sendPacket(ClientProtocol.U_EVEFEAST_ENTER_GAME, respMsg);
            return 0;
        }

        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfigByTurn(missionId, 1);
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        int costType = 0;
        if (missionId != 0) {//试玩不消耗次数和道具
            if (userData.getGameTimes() >= EveFeastMgr.getConfig().getDayNum()) {
                costType = 1;
                if (!player.getModule(CurrencyModule.class).removeCurrency(EveFeastMgr.getConfig().getEnergyCost(), eLogMoneyType.EveFeast, eLogMoneyType.EveFeastStartGameCost)) {
                    return GameErrorCode.E_EVEFEAST_DAY_NUM_LIMIT;
                }
            }
            userData.setGameTimes(userData.getGameTimes() + 1);
            userData.setLastGameTime(DateHelper.getCurrentTime());
        }

        //创建新游戏
        EveFeastGameData newGameData = new EveFeastGameLogic(EveFeastMgr.getConfig(), randomHelper).createNewGameData(missionConfig, userData.getBuyToken1(), userData.getBuyToken2());
        if (missionConfig.getMission() == 0) {
            userData.setPracticeData(newGameData);
        } else {
            userData.setGameData(newGameData);
        }
        //因为要补发评价奖励,所以每次游宴都要记录评价奖励
        int appraise = 0;
        Property appraiseReward = new Property();
        if (missionId != 0) {
            appraise = EveFeastMgr.getConfig().calcEveFeastAppraise(0);
            appraiseReward = EveFeastMgr.getConfig().getAppraiseReward(appraise);
            userData.setAutoReward(PropertyHelper.parsePropertyToString(appraiseReward));
        }

        userData.setUpdateOption();

        EveFeastProto.EveFeastGameTemp.Builder gameMsg = EveFeastPb.parseGameDataMsg(newGameData);
        EveFeastProto.EveFeastEnterGameRespMsg.Builder respMsg = EveFeastProto.EveFeastEnterGameRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setGameScene(gameMsg);
        player.sendPacket(ClientProtocol.U_EVEFEAST_ENTER_GAME, respMsg);

//        syncUserMsg();

        if (missionConfig.getMission() != 0) {
            AutoLogMgr.add(new LogEveFeastNewGame(userData.getActivityId(), userData.getUserId(), costType, missionConfig.getTurnId(), userData.getGameTimes(), JSON.toJSONString(userData.getGameData().getChoseItems())));
        }

        return 0;
    }

    /**
     * 选择物品
     */
    public int choseItem(int itemId, int mission) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        EveFeastGameData gameData;
        if (mission == 0) {
            gameData = userData.getPracticeData();
        } else {
            gameData = userData.getGameData();
        }

        if (gameData == null) {
            return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
        }

        if (gameData.getChoseItems().isEmpty()) {
            return GameErrorCode.E_EVEFEAST_CHOSE_ITEM_EMPTY;
        }
        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfig(gameData.getTurnId());
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        if (itemId != 0 && !gameData.getChoseItems().contains(itemId)) {
            return GameErrorCode.E_EVEFEAST_CHOSE_ITEM_NOT_FOUND;
        }

        gameData.getChoseItems().clear();

        userData.setUpdateOption();

        EveFeastProto.EveFeastItemChoseRespMsg.Builder respMsg = EveFeastProto.EveFeastItemChoseRespMsg.newBuilder();
        respMsg.setRet(0);
        if (itemId != 0) {
            EveFeastGameLogic gameLogic = new EveFeastGameLogic(EveFeastMgr.getConfig(), randomHelper);
            gameLogic.createNewGameItem(gameData, itemId);
        }
        respMsg.addAllHaveItems(EveFeastPb.parseGameItemListMsg(gameData.getHaveItems()));

        player.sendPacket(ClientProtocol.U_EVEFEAST_ITEM_CHOSE, respMsg);

        syncUserMsg();

        if (missionConfig.getMission() != 0) {//非试玩才记录日志
            AutoLogMgr.add(new LogEveFeastChoseItem(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId(), gameData.getTurnId(), itemId));
        }

        return 0;
    }

    /**
     * 刷新物品
     */
    public int refreshItem(boolean isCost, int mission) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        EveFeastGameData gameData;
        if (mission == 0) {
            gameData = userData.getPracticeData();
        } else {
            gameData = userData.getGameData();
        }

        if (gameData == null) {
            return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
        }

        if (gameData.getChoseItems().isEmpty()) {
            return GameErrorCode.E_EVEFEAST_CHOSE_ITEM_EMPTY;
        }

        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfig(gameData.getTurnId());
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        if (gameData.getRefreshTimes() <= 0) {
            if (!isCost || missionConfig.getMission() == 0) {
                return GameErrorCode.E_EVEFEAST_REFRESH_TIMES_LIMIT;
            } else {
                if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(EveFeastMgr.getConfig().getRefreshItemId(), 1), eLogMoneyType.EveFeast, eLogMoneyType.EveFeastRefreshCost)) {
                    return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                }
            }
        }

        if (gameData.getRefreshTimes() > 0) {
            gameData.setRefreshTimes(gameData.getRefreshTimes() - 1);
        }
        List<Integer> logItemIds = new ArrayList<>();
        if (userData.getBuyToken2() && missionConfig.getTurn() == 1 && gameData.getRound() == 1) {//高级战令效果,第一回合有专门的随机池
            Map<Integer, Integer> token2RandomPool = EveFeastMgr.getConfig().getToken2RandomPool();
            for (Integer itemId : gameData.getChoseItems()) {
                token2RandomPool.remove(itemId);
            }
            gameData.getChoseItems().clear();
            for (int i = 0; i < 3; i++) {
                Integer itemId = RandomHelper.getRandomKeyByWeight(token2RandomPool);
                new EveFeastGameLogic(EveFeastMgr.getConfig(), randomHelper).addChoseItem(gameData, itemId);
                token2RandomPool.remove(itemId);
                logItemIds.add(itemId);
            }
        } else {
            //随机3个物品
            List<Integer> itemIds = EveFeastMgr.getConfig().randomItemList(gameData, missionConfig, 3);

            gameData.getChoseItems().clear();
            for (Integer itemId : itemIds) {
                new EveFeastGameLogic(EveFeastMgr.getConfig(), randomHelper).addChoseItem(gameData, itemId);
                logItemIds.add(itemId);
            }
        }

        userData.setUpdateOption();

        EveFeastProto.EveFeastItemRefreshRespMsg.Builder respMsg = EveFeastProto.EveFeastItemRefreshRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.addAllChoseItem(gameData.getChoseItems());

        player.sendPacket(ClientProtocol.U_EVEFEAST_ITEM_REFRESH, respMsg);

        syncUserMsg();

        if (missionConfig.getMission() != 0) {//非试玩才记录日志
            AutoLogMgr.add(
                    new LogEveFeastRefreshItem(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId(),
                            isCost ? 1 : 0, gameData.getTurnId(), gameData.getRefreshTimes(), JSON.toJSONString(logItemIds)));
        }
        return 0;
    }

    /**
     * 选择BUFF
     */
    public int choseBuff(int buffId, int mission) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        EveFeastGameData gameData;
        if (mission == 0) {
            gameData = userData.getPracticeData();
        } else {
            gameData = userData.getGameData();
        }

        if (gameData == null) {
            return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
        }

        if (gameData.getChoseBuffs().isEmpty()) {
            return GameErrorCode.E_EVEFEAST_CHOSE_BUFF_EMPTY;
        }

        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfig(gameData.getTurnId());
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        if (!gameData.getChoseBuffs().contains(buffId)) {
            return GameErrorCode.E_EVEFEAST_CHOSE_BUFF_NOT_FOUND;
        }

        gameData.getChoseBuffs().clear();
        gameData.getHaveBuffs().clear();//只保留一个BUFF

        gameData.addHaveBuff(buffId);
        //选完BUFF处理立即生效的BUFF效果,进入下一轮
        EveFeastGameLogic eveFeastGameLogic = new EveFeastGameLogic(EveFeastMgr.getConfig(), randomHelper);
        eveFeastGameLogic.handleChoseBuffEffect(gameData);

        //防止三选一里在选完BUFF有不可重复的,再随机一次三选一
        //随机3个物品
        List<Integer> itemIds = EveFeastMgr.getConfig().randomItemList(gameData, missionConfig, 3);

        gameData.getChoseItems().clear();
        for (Integer itemId : itemIds) {
            new EveFeastGameLogic(EveFeastMgr.getConfig(), randomHelper).addChoseItem(gameData, itemId);
        }

        userData.setUpdateOption();

        EveFeastProto.EveFeastBuffChoseRespMsg.Builder respMsg = EveFeastProto.EveFeastBuffChoseRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setGameScene(EveFeastPb.parseGameDataMsg(gameData));
        for (Integer addItemId : eveFeastGameLogic.getAddItemIds()) {
            respMsg.addNewItemId(addItemId);
        }

        player.sendPacket(ClientProtocol.U_EVEFEAST_BUFF_CHOSE, respMsg);

        syncUserMsg();

        if (missionConfig.getMission() != 0) {//非试玩才记录日志
            AutoLogMgr.add(
                    new LogEveFeastChoseBuff(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId(),
                            gameData.getTurnId(), buffId));
        }
        return 0;
    }

    /**
     * 刷新BUFF
     */
    public int refreshBuff(boolean isCost, int mission) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        EveFeastGameData gameData;
        if (mission == 0) {
            gameData = userData.getPracticeData();
        } else {
            gameData = userData.getGameData();
        }

        if (gameData == null) {
            return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
        }

        if (gameData.getChoseBuffs().isEmpty()) {
            return GameErrorCode.E_EVEFEAST_CHOSE_BUFF_EMPTY;
        }

        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfig(gameData.getTurnId());
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        if (gameData.getRefreshTimes() <= 0) {
            if (!isCost || missionConfig.getMission() == 0) {
                return GameErrorCode.E_EVEFEAST_REFRESH_TIMES_LIMIT;
            } else {
                if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(EveFeastMgr.getConfig().getRefreshItemId(), 1), eLogMoneyType.EveFeast, eLogMoneyType.EveFeastRefreshCost)) {
                    return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                }
            }
        }

        if (gameData.getRefreshTimes() > 0) {
            gameData.setRefreshTimes(gameData.getRefreshTimes() - 1);
        }

        //随机3个祝酒词
        List<Integer> greetingIds = EveFeastMgr.getConfig().randomGreetingId(gameData, missionConfig, 3);

        gameData.getChoseBuffs().clear();
        for (Integer greetingId : greetingIds) {
            gameData.getChoseBuffs().add(greetingId);
        }
        userData.setUpdateOption();

        EveFeastProto.EveFeastBuffRefreshRespMsg.Builder respMsg = EveFeastProto.EveFeastBuffRefreshRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.addAllChoseBuff(gameData.getChoseBuffs());

        player.sendPacket(ClientProtocol.U_EVEFEAST_BUFF_REFRESH, respMsg);

        if (missionConfig.getMission() != 0) {//非试玩才记录日志
            AutoLogMgr.add(
                    new LogEveFeastRefreshBuff(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId(), isCost ? 1 : 0,
                            gameData.getTurnId(), gameData.getRefreshTimes(), JSON.toJSONString(greetingIds)));
        }
        return 0;
    }

    /**
     * 开始游宴,算回合积分, testJson是测试才用的
     */
    public int startCalcRoundScore(String testJson, int mission) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        EveFeastGameData gameData;
        if (mission == 0) {
            if (userData.getPracticeData() == null) {
                return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
            }
            gameData = userData.getPracticeData().clone();
        } else {
            if (userData.getGameData() == null) {
                return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
            }
            gameData = userData.getGameData().clone();
        }

        if (!gameData.getChoseBuffs().isEmpty()) {
            return GameErrorCode.E_EVEFEAST_CHOSE_BUFF_NEED_DEAL;
        }

        if (!gameData.getChoseItems().isEmpty()) {
            return GameErrorCode.E_EVEFEAST_CHOSE_ITEM_NEED_DEAL;
        }

        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfig(gameData.getTurnId());
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        EveFeastProto.EveFeastStartRandomRespMsg.Builder respMsg = EveFeastProto.EveFeastStartRandomRespMsg.newBuilder();
        respMsg.setRet(0);

        if (ServerListMgr.getChannelId(GameServer.getInstance().getServerId()) != 666) {
            testJson = "";
        }

        //开始游宴
        EveFeastGameLogic gameLogic = new EveFeastGameLogic(EveFeastMgr.getConfig(), randomHelper);
        gameLogic.startRandomPlaceItem(gameData, userData.getBuyToken1(), userData.getBuyToken2(), testJson);

        respMsg.setGameScene(EveFeastPb.parseGameDataMsg(gameData));
        respMsg.addAllShowGroup(EveFeastPb.parseShowGroupMsg(gameLogic.getShowInfoListList()));
        respMsg.setIsNextRound(gameLogic.isNextRound());
        respMsg.setIsNextTurn(gameLogic.isNextTurn());
        respMsg.setIsEnd(gameLogic.isEnd());
        respMsg.setIsPass(gameLogic.isPass());
        respMsg.setRefreshAdd(gameLogic.getRefreshAdd());
        respMsg.setRemoveAdd(gameLogic.getRemoveAdd());

        if (missionConfig.getMission() != 0) {//试玩没有成就和榜单值
            checkActivityCondition(gameData, gameLogic.isEnd());
        }

        if (missionConfig.getMission() != 0) {
            AutoLogMgr.add(new LogEveFeastPlay(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId(),
                    gameData.getTurnId(), gameData.getRound(), gameData.getScore(), gameData.getRemainScore(), gameLogic.isEnd(), false, gameLogic.getInitOnItemList(),
                    gameLogic.getAddPlaceOnItemList(), gameLogic.getEliminateItemList()));
        }
        //因为要补发评价奖励,所以每次游宴都要记录评价奖励
        int appraise = 0;
        Property appraiseReward = new Property();
        if (mission != 0) {
            appraise = EveFeastMgr.getConfig().calcEveFeastAppraise(gameData.getScore());
            appraiseReward = EveFeastMgr.getConfig().getAppraiseReward(appraise);
            userData.setAutoReward(PropertyHelper.parsePropertyToString(appraiseReward));
        }
        if (gameLogic.isEnd()) {
            //游戏结束,发送评价奖励
            respMsg.setScoreAppraise(appraise + 1);
            if (missionConfig.getMission() != 0) {//非试玩才有成就和评价奖励
                if (!appraiseReward.isNothing()) {
                    player.getModule(CurrencyModule.class).addCurrency(appraiseReward, eLogMoneyType.EveFeast, eLogMoneyType.EveFeastAppraiseReward);
                    respMsg.setReward(PropertyHelper.parsePropertyToString(appraiseReward));
                }
            }
            respMsg.setMaxScore(userData.getMaxScore());

            gameData = null;
            userData.setAutoReward("");//结算要置空
        }


        if (mission == 0) {
            userData.setPracticeData(gameData);
        } else {
            userData.setGameData(gameData);
        }

        userData.setUpdateOption();

        player.sendPacket(ClientProtocol.U_EVEFEAST_START_RANDOM, respMsg);

        syncUserMsg();

        return 0;

    }

    public int removeItem(int id, boolean isCost, int mission) {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        EveFeastGameData gameData;
        if (mission == 0) {
            gameData = userData.getPracticeData();
        } else {
            gameData = userData.getGameData();
        }

        if (gameData == null) {
            return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
        }

        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfig(gameData.getTurnId());
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        if (gameData.getRemoveTimes() <= 0) {
            if (!isCost || missionConfig.getMission() == 0) {
                return GameErrorCode.E_EVEFEAST_REMOVE_TIMES_LIMIT;
            } else {
                if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(EveFeastMgr.getConfig().getEliminateItemId(), 1), eLogMoneyType.EveFeast, eLogMoneyType.EveFeastRemoveCost)) {
                    return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                }
            }
        }

        if (gameData.getRemoveTimes() > 0) {
            gameData.setRemoveTimes(gameData.getRemoveTimes() - 1);
        }

        EveFeastItem removeItem = null;
        for (EveFeastItem haveItem : gameData.getHaveItems()) {
            if (haveItem.getId() == id) {
                removeItem = haveItem;
                break;
            }
        }
        if (removeItem == null) {
            return GameErrorCode.E_EVEFEAST_BAG_ITEM_NOT_FOUND;
        }

        gameData.getHaveItems().remove(removeItem);
        for (List<EveFeastBlock> blocks : gameData.getBlocks()) {
            for (EveFeastBlock block : blocks) {
                if (block.getObjectId() == removeItem.getId()) {
                    block.clearItem();
                }
            }
        }

        userData.setUpdateOption();

        EveFeastProto.EveFeastRemoveItemRespMsg.Builder respMsg = EveFeastProto.EveFeastRemoveItemRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.addAllHaveItem(EveFeastPb.parseGameItemListMsg(gameData.getHaveItems()));

        player.sendPacket(ClientProtocol.U_EVEFEAST_REMOVE_ITEM, respMsg);

        syncUserMsg();

        if (missionConfig.getMission() != 0) {//非试玩才记录日志
            AutoLogMgr.add(
                    new LogEveFeastRemoveItem(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId(), isCost ? 1 : 0,
                            gameData.getTurnId(), gameData.getRemoveTimes(), removeItem.getId(), removeItem.getItemId()));
        }

        return 0;
    }

    public int cancelGame(int mission) {
        if (userData == null) {
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }

        if (EveFeastMgr.getConfig() == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        EveFeastGameData gameData;
        if (mission == 0) {
            gameData = userData.getPracticeData();
        } else {
            gameData = userData.getGameData();
        }

        if (gameData == null) {
            return GameErrorCode.E_EVEFEAST_GAME_EMPTY;
        }

        EveFeastMissionConfig missionConfig = EveFeastMgr.getConfig().getMissionConfig(gameData.getTurnId());
        if (missionConfig == null) {
            return GameErrorCode.E_EVEFEAST_CONFIG_NOT_FOUND;
        }

        EveFeastProto.EveFeastCancelGameRespMsg.Builder respMsg = EveFeastProto.EveFeastCancelGameRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setGameScene(EveFeastPb.parseGameDataMsg(gameData));

        //游戏结束,计算评价
        int appraise = EveFeastMgr.getConfig().calcEveFeastAppraise(gameData.getScore());
        respMsg.setScoreAppraise(appraise + 1);
        if (missionConfig.getMission() != 0) {//非试玩才有成就和评价奖励
            Property appraiseReward = EveFeastMgr.getConfig().getAppraiseReward(appraise);
            if (!appraiseReward.isNothing()) {
                player.getModule(CurrencyModule.class).addCurrency(appraiseReward, eLogMoneyType.EveFeast, eLogMoneyType.EveFeastAppraiseReward);
                respMsg.setReward(PropertyHelper.parsePropertyToString(appraiseReward));
            }

            checkActivityCondition(gameData, true);
        }
        respMsg.setMaxScore(userData.getMaxScore());

        userData.setAutoReward("");//结算要置空
        if (mission == 0) {
            userData.setPracticeData(null);
        } else {
            userData.setGameData(null);
        }

        player.sendPacket(ClientProtocol.U_EVEFEAST_CANCEL_GAME, respMsg);

        syncUserMsg();

        if (missionConfig.getMission() != 0) {
            AutoLogMgr.add(new LogEveFeastPlay(EveFeastMgr.getActivityInfo().getActivityId(), player.getUserId(),
                    gameData.getTurnId(), gameData.getRound(), gameData.getScore(), gameData.getRemainScore(), true, true));
        }

        return 0;
    }

    public void rechargeToken(int activityId, MallInfo mallInfo) {
        if (EveFeastMgr.getConfig() == null) {
            return ;
        }

        if (!ActivityMgr.activityInShowTime(EveFeastMgr.getActivityInfo())) {
            return;
        }
        if (userData.getActivityId() != activityId) {
            return;
        }

        if (mallInfo.getShopType() == eShopType.ChineseChessSilverToken.getValue()) {
            player.notifyListener(eGamePlayerEventType.EveFeastInvite2.getValue(), userData.getMaxScore());
            userData.setBuyToken1(true);
        }
        if (mallInfo.getShopType() == eShopType.ChineseChessGoldToken.getValue()) {
            player.notifyListener(eGamePlayerEventType.EveFeastInvite3.getValue(), userData.getMaxScore());
            userData.setBuyToken2(true);
        }

        syncUserMsg();

    }

    public boolean isBuyToken(MallInfo mallInfo) {
        if (mallInfo.getShopType() == eShopType.ChineseChessSilverToken.getValue()) {
            return userData.getBuyToken1();
        }
        if (mallInfo.getShopType() == eShopType.ChineseChessGoldToken.getValue()) {
            return userData.getBuyToken2();
        }
        return true;
    }

    public UserEveFeastData getUserData() {
        return userData;
    }

    public synchronized void checkActivityCondition(EveFeastGameData gameData, boolean isEnd) {
        if (gameData.getScore() > userData.getMaxScore()) {
            userData.setMaxScore(gameData.getScore());
            userData.setMaxScoreItems(gameData.getHaveItems());

            player.notifyListener(eGamePlayerEventType.EveFeastUserRank.getValue(), userData.getMaxScore());
            player.notifyListener(eGamePlayerEventType.EveFeastInvite.getValue(), userData.getMaxScore());
            if (userData.getBuyToken1()) {
                player.notifyListener(eGamePlayerEventType.EveFeastInvite2.getValue(), userData.getMaxScore());
            }
            if (userData.getBuyToken2()) {
                player.notifyListener(eGamePlayerEventType.EveFeastInvite3.getValue(), userData.getMaxScore());
            }
        }

//        if (isEnd) {
//            Property endItemProperty = new Property();
//            for (EveFeastItem haveItem : gameData.getHaveItems()) {
//                endItemProperty.addProperty(haveItem.getItemId(), BigInteger.ONE);
//            }
//            player.notifyListener(eGamePlayerEventType.EveFeastGameEndAchieve.getValue(), endItemProperty);
//        } else {
//            player.notifyListener(eGamePlayerEventType.EveFeastGameAchieve.getValue(), gameData.getWasGetItems());
//        }

    }

    public synchronized List<EveFeastItem> getMaxScoreItems() {
        List<EveFeastItem> maxScoreItems = new ArrayList<>();
        if (userData == null) {
            return maxScoreItems;
        }
        maxScoreItems.addAll(userData.getMaxScoreItems());
        return maxScoreItems;
    }

    public int skipGuide() {
        int ret = checkActivityRet();
        if (ret != 0) {
            return ret;
        }

        userData.setGuideStep(1);
        player.sendPacket(ClientProtocol.U_EVEFEAST_SKIP_GUIDE, EveFeastProto.EveFeastSkipGuideRespMsg.newBuilder().setRet(0));

        syncUserMsg();

        return 0;
    }


}
